package net.koodar.forge.system.dept.service;

import lombok.RequiredArgsConstructor;
import net.koodar.forge.system.dept.model.dto.DeptParamDTO;
import net.koodar.forge.system.dept.model.entity.Dept;
import net.koodar.forge.system.dept.model.vo.DeptVO;
import net.koodar.forge.system.dept.manager.DeptManager;
import net.koodar.forge.common.code.UserErrorCode;
import net.koodar.forge.common.domain.dto.MultiResponse;
import net.koodar.forge.common.domain.dto.Response;
import net.koodar.forge.system.dept.service.assembler.DeptAssembler;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liyc
 */
@Service
@RequiredArgsConstructor
public class DeptService {

	private final DeptManager deptManager;
	private final DeptAssembler deptAssembler;

	/**
	 * 获取Tree结构的部门列表
	 * @return 部门Tree
	 */
	public Response listTree() {
		List<Dept> deptList = deptManager.list();
		List<DeptVO> tree = deptAssembler.convertToTree(null, deptList);
		return MultiResponse.ok(tree);
	}

	/**
	 * 添加部门
	 * @param deptParamDTO 部门参数
	 */
	public Response addDept(DeptParamDTO deptParamDTO) {
		Dept dbDept = deptManager.findByParentIdAndDeptName(deptParamDTO.getParentId(), deptParamDTO.getDeptName());
		if (dbDept != null) {
			return Response.error(UserErrorCode.ALREADY_EXIST, String.format("当前部门下已存在名称为[%s]的部门", deptParamDTO.getDeptName()));
		}

		Dept dept = deptAssembler.convertToDept(deptParamDTO);
		deptManager.save(dept);
		return Response.ok();
	}

	/**
	 * 修改部门
	 * @param deptParamDTO 部门参数
	 */
	public Response updateDept(DeptParamDTO deptParamDTO) {
		Dept dbDept = deptManager.findByParentIdAndDeptName(deptParamDTO.getParentId(), deptParamDTO.getDeptName());
		if (dbDept != null) {
			if (!dbDept.getId().equals(deptParamDTO.getId())) {
				return Response.error(UserErrorCode.ALREADY_EXIST, String.format("当前部门下已存在名称为[%s]的部门", deptParamDTO.getDeptName()));
			}
		}

		Dept dept = deptManager.findById(deptParamDTO.getId());
		deptAssembler.convertToDept(dept, deptParamDTO);
		deptManager.save(dept);
		return Response.ok();
	}

	/**
	 * 删除部门
	 * @param id 部门id
	 */
	public Response deleteDept(Long id) {
		deptManager.removeById(id);
		return Response.ok();
	}


}
